package cn.hengzhu.main_manager.web.controller;

import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseUsetimeMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCompMapper;
import cn.hengzhu.main_manager.repository.domain.*;
import cn.hengzhu.main_manager.repository.param.CaseUseTimeParam;
import cn.hengzhu.main_manager.repository.param.UseEndTimeParam;
import cn.hengzhu.main_manager.repository.vo.CaseUseTypeVO;
import cn.hengzhu.main_manager.repository.vo.ManageCaseUseTimeVO;
import cn.hengzhu.main_manager.utils.*;
import cn.hengzhu.main_manager.utils.ann.MoblieUrl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/caseUseTime")
public class CaseUseTimeController {
	@Autowired
	private ManageCaseUsetimeMapper manageCaseUsetimeMapper;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;

	@MoblieUrl
	@RequestMapping("/index")
	public String caseUseTime(Model model) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<ManageCase> selectByExample = new ArrayList<>();
		ManageCaseExample mce = new ManageCaseExample();
		if (compId.equals(0)) {
			selectByExample = manageCaseMapper.selectByExample(mce);
			List<ManageComp> compList = manageCompMapper.selectByExample(new ManageCompExample());
			model.addAttribute("comps", compList);
		} else {
			mce.createCriteria().andCompIdEqualTo(compId);//公司id
			selectByExample = manageCaseMapper.selectByExample(mce);
		}

		if (!selectByExample.isEmpty()) {
			Map<Byte, Long> collect = selectByExample.stream().collect(Collectors.groupingBy(ManageCase::getUseType, Collectors.counting()));
			List<CaseUseTypeVO> TypeList = new ArrayList<>();
			collect.forEach((k, v) -> {
				CaseUseTypeVO c = new CaseUseTypeVO();
				c.setKindId(k.intValue());
				c.setNum(v.intValue());
				if (k == 1) {
					c.setKindName("普通储物柜");
				} else if (k == 2) {
					c.setKindName("医用床");
				} else if (k == 3) {
					c.setKindName("快递柜");
				} else if (k == 4) {
					c.setKindName("快餐");
				} else if (k == 5) {
					c.setKindName("成人用品柜");
				} else if (k == 6) {
					c.setKindName("智能医药柜");
				} else if (k == 7) {
					c.setKindName("自动柜");
				}
				TypeList.add(c);
			});

			int sum = TypeList.stream().mapToInt(CaseUseTypeVO::getNum).sum();

			CaseUseTypeVO c = new CaseUseTypeVO();
			c.setKindId(0);
			c.setKindName("全部");
			c.setNum(sum);
			TypeList.add(0, c);

			model.addAttribute("type", TypeList);
		}
		return request.getAttribute("moblie") + "caseUseTime";
	}

	@MoblieUrl
	@RequestMapping("/edit")
	public String edit() {
		return request.getAttribute("moblie") + "caseUseTimeEdit";
	}

	/**
	 * @param param
	 * @return 储物柜使用时间列表
	 * @throws ParseException
	 * @author liuCheng
	 * @since 2018年11月16日 下午2:57:36
	 */
	@ResponseBody
	@RequestMapping("/list")
	public LayUiResultJson<ManageCaseUseTimeVO> list(CaseUseTimeParam param) {

		int compId = param.getCompId();
		String like = param.getLike();
		Byte useTypeId = param.getUseTypeId();

		ManageCaseExample manageCaseExample = new ManageCaseExample();
		ManageCaseExample.Criteria criteria = manageCaseExample.createCriteria();

		if(compId != -1){
			criteria.andCompIdEqualTo(compId);
		}
		if(useTypeId != 0){
			criteria.andUseTypeEqualTo(useTypeId);
		}
		criteria.andCaseNoLike(like);

		PageHelper.startPage(param.getPage(), param.getLimit(), true);
		List<ManageCase> manageCases = manageCaseMapper.selectByExample(manageCaseExample);
		PageInfo<ManageCase> pageInfo = new PageInfo<>(manageCases);

		//符合条件的caseNo 表box
		List<String> caseNOs = manageCases.stream().collect(Collectors.mapping(ManageCase::getCaseNo,Collectors.toList()));


		List<ManageCaseUseTimeVO> list = new ArrayList<>();
		List<ManageCaseUsetime> manageCaseUsetimeList = manageCaseUsetimeMapper.getUseEndTimeList(param);
		manageCaseUsetimeList.stream().forEach(a -> {
			ManageCaseUseTimeVO manageCaseUseTimeVO = new ManageCaseUseTimeVO();
			manageCaseUseTimeVO.setUseTimeId(a.getId());
			manageCaseUseTimeVO.setCaseNo(a.getCaseNo());
			manageCaseUseTimeVO.setDes(a.getDes());
			manageCaseUseTimeVO.setLatitude(a.getLatitude());
			manageCaseUseTimeVO.setLongitude(a.getLongitude());
			manageCaseUseTimeVO.setUseTime(DateTimeHelper.formatDateTimetoString(a.getUseEndTime(), "yyyy-MM-dd HH:mm:ss"));
			list.add(manageCaseUseTimeVO);
		});

		//符合条件的caseNo case过期表
		List<String> caseList = list.stream().collect(Collectors.mapping(ManageCaseUseTimeVO::getCaseNo,Collectors.toList()));
//        if(caseNOs.size() == list.size()){
//            Collection exists=new ArrayList<String>(caseNOs);
//            exists.removeAll(caseList);
//            System.out.println(exists.size());
//            exists.stream().forEach(a->{
//                ManageCaseUsetime manageCaseUsetime = new ManageCaseUsetime();
//                manageCaseUsetime.setCaseNo(a.toString());
//                manageCaseUsetime.setUseEndTime(new Date());
//                manageCaseUsetime.setCreateTime(new Date());
//                manageCaseUsetimeMapper.insertSelective(manageCaseUsetime);
//            });
//        }

		List<String> intersection = caseNOs.stream().filter(item -> caseList.contains(item)).collect(Collectors.toList());

		List<ManageCaseUseTimeVO> result1 =  list.stream().filter(item -> intersection.contains(item.getCaseNo())).collect(Collectors.toList());



		long count = pageInfo.getTotal();
		LayUiResultJson<ManageCaseUseTimeVO> result = new LayUiResultJson<ManageCaseUseTimeVO>();
		result.setCount(count);
		result.setData(result1);
		return result;
	}

	/**
	 * @param param
	 * @return 设置使用时间
	 * @throws Exception
	 * @author liuCheng
	 * @since 2018年11月16日 下午3:02:29
	 */
	@ResponseBody
	@RequestMapping("/setUseEndTime")
	public AjaxResult setUseEndTime(UseEndTimeParam param) throws Exception {
		List<String> caseNos = param.getCaseNo();
		String useEndTime = param.getUseEndTime();

		if (StringUtils.isNotBlank(useEndTime)) {
			Date parseToDate = DateTimeHelper.parseToDate(useEndTime, "yyyy-MM-dd HH:mm:ss");

			ManageCaseUsetime manageCaseUsetime = new ManageCaseUsetime();
			manageCaseUsetime.setUseEndTime(parseToDate);
			ManageCaseUsetimeExample manageCaseUsetimeExample = new ManageCaseUsetimeExample();
			manageCaseUsetimeExample.createCriteria().andCaseNoIn(caseNos);
			try {
				int updateByExampleSelective = manageCaseUsetimeMapper.updateByExampleSelective(manageCaseUsetime,
						manageCaseUsetimeExample);
				if (updateByExampleSelective > 0) {
					long date = new Date().getTime();
					long time = parseToDate.getTime();
					if (date < time) {
						for (String caseNo: caseNos) {
							Connection connection = ConnectionUtils.getConnection();
							Channel channel = connection.createChannel();
							Map<String, Object> sendMap = new HashMap<>();
							sendMap.put("code", 1);
							ObjectMapper mapper = new ObjectMapper();
							Map<String, Object> args = new HashMap<String, Object>();
							args.put("x-message-ttl", 40000);
							channel.queueDeclare(caseNo, true, false, false, args);
							String writeValueAsString = mapper.writeValueAsString(sendMap);
							channel.basicPublish("", caseNo, null, writeValueAsString.getBytes());
							channel.close();
							connection.close();
						}
					}
					return new AjaxResult();
				} else {
					return new AjaxResult("修改失败222");
				}
			} catch (Exception e) {
				return new AjaxResult("修改失败111");
			}

		} else {
			return new AjaxResult();

		}

	}

	/**
	 * @param param
	 * @return
	 * @throws Exception 修改描述信息
	 * @author liuCheng
	 * @since 2018年12月19日 下午4:40:57
	 */
	@ResponseBody
	@RequestMapping("/editMyDes")
	public AjaxResult editMyDes(UseEndTimeParam param) {
		Integer useTimeId = param.getUseTimeId();
		String des = param.getDes();
		if (StringUtils.isNotBlank(des)) {

			ManageCaseUsetime record = new ManageCaseUsetime();
			record.setId(useTimeId);
			record.setDes(des);
			try {
				manageCaseUsetimeMapper.updateByPrimaryKeySelective(record);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("修改失败");
			}

		} else {
			return new AjaxResult("修改失败");

		}
	}

}
